package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.cart.pojo.Cart;
import com.dongdongshop.cart.pojo.TbOrderItem;
import com.dongdongshop.cart.service.CartService;
import com.dongdongshop.seller.pojo.TbItem;
import com.dongdongshop.seller.service.ItemService;
import com.dongdongshop.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
@Service
public class CartServiceImpl implements CartService {

    @Reference(check = false,timeout = 50000)
    private ItemService itemService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;

    @Override
    public List<Cart> getCartByRedis(String username) {
        System.out.println("从redis中提取购物车数据{},{},{}"+username);
        List<Cart> cartList=(List<Cart>)redisTemplate.boundHashOps("cartList").get(username);
        //避免空指针，进行判断
        if(cartList == null){
            cartList=new ArrayList<>();
        }
        return cartList;
    }

    @Override
    public List<Cart> addToCart(List<Cart> cartList, Long itemId, Integer num) {
        //根据商品sku id 查询sku商品信息
        TbItem item = itemService.getItemByid(itemId);
        //获取商家id
        String sellerId = item.getSellerId();
        //根据商家id判断购物车列表中是否存在该商家的购物车
        Cart ct = searchorderitembyitemid(sellerId, cartList);
        //如果购物车列表中不存在该商家的购物车
        if (ct == null){
            //新建购物车对象
            ct = new Cart();
            ct.setSellerId(sellerId);
            ct.setSellerName(item.getSeller());
            //将商品的sku数据保存在订单明细表中
            TbOrderItem tbOrderItem = getTbOrderItem(item, num);
            List<TbOrderItem> orderItemList = new ArrayList<>();
            orderItemList.add(tbOrderItem);
            ct.setOrderItemList(orderItemList);
            //将新建的购物车对象添加到购物车列表
            cartList.add(ct);
        }else {
            //5.如果购物车列表中存在该商家的购物车
            // 5.1查询购物车明细列表中是否存在该商品
            List<TbOrderItem> orderItemList = ct.getOrderItemList();
            TbOrderItem tbOrderItemById = getTbOrderItemById(orderItemList, item);
            //如果没有，新增购物车明细
            if (tbOrderItemById == null){
                tbOrderItemById = getTbOrderItem(item,num);
                ct.getOrderItemList().add(tbOrderItemById);
            }else {
                //如果有，在元购物车明细上添加数量，更改金额
                tbOrderItemById.setNum(tbOrderItemById.getNum()+num);
                //总价格
                tbOrderItemById.setTotalFee(new BigDecimal(tbOrderItemById.getNum() * tbOrderItemById.getPrice().doubleValue()));
                //如果数量加完只是num <= 0 我们把它移除掉，而不是继续保留
                if (tbOrderItemById.getNum() <= 0){
                    ct.getOrderItemList().remove(tbOrderItemById);
                }
                //如果移出后OrderItemList大小为0，那么我们将这个cart给移除掉
                if (ct.getOrderItemList().size() <= 0){
                    cartList.remove(ct);
                }

            }

        }
        return cartList;
    }

    //根据商家id查询购物车列表中的商家购物车
    public Cart searchorderitembyitemid(String sellerId,List<Cart> cartList){
        return cartList.stream().filter(x ->x.getSellerId().equals(sellerId)).findFirst().orElse(null);

        /*for (Cart orderItem : cartList){
            //判断购物车中是否有商家的Id,如果有把数据返回去
            if(orderItem.getSellerId().equals(sellerId)){
                return orderItem;
            }
        }
        return null;*/
    }
    //将商品的数据保存到订单对象中
    public TbOrderItem getTbOrderItem(TbItem item,Integer num){
        TbOrderItem orderItem = new TbOrderItem();
        orderItem.setId(idWorker.nextId());
        orderItem.setGoodsId(item.getGoodsId());
        orderItem.setItemId(item.getId());
        orderItem.setNum(num);
        orderItem.setPicPath(item.getImage());
        orderItem.setPrice(item.getPrice());
        orderItem.setTitle(item.getTitle());
        orderItem.setSellerId(item.getSellerId());
        //总价格=单价 * 数量
        orderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue() * num));
        orderItem.setTitle(item.getTitle());
        return orderItem;
    }
    //根据商品id查询购物车明细中商品的数据
    public TbOrderItem getTbOrderItemById(List<TbOrderItem> orderItemList,TbItem item){

       return orderItemList.stream().filter(x -> x.getItemId().equals(item.getId())).findFirst().orElse(null);
        /*for (TbOrderItem orderItem : orderItemList) {
            if (orderItem.getItemId().equals(item.getId())){
                return orderItem;
            }

        }*/
    }
    //合并redis和connkie的购物车
    @Override
    public List<Cart> mergeCartlist(List<Cart> redisCart, List<Cart> carts) {
        for (Cart cart : redisCart) {
            for (TbOrderItem orderItem : cart.getOrderItemList()) {
                carts = addToCart(carts,orderItem.getItemId(),orderItem.getNum());
            }
        }
        return carts;
    }

    @Override
    public void addCartRedis(String username, List<Cart> mergeCartlist) {
        System.out.println("想redis中添加购物车数据{},{},{}"+username);
        redisTemplate.boundHashOps("cartList").put(username,mergeCartlist);
        System.out.println("购物车数据保存成功");
    }
}
